﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using SharedLibraries;
using SharedLibraries.Constants;
using ThangNM_LIB.DB;
using ThangNM_LIB.EO;
using ThangNM_LIB.FUNC;
using System.IO;

namespace ThangNM.UserControl.Admin
{
    public partial class AdminUC : System.Web.UI.UserControl
    {
        public AccountEO objTemp
        {
            get { return (AccountEO)ViewState["objTemp"]; }
            set { ViewState["objTemp"] = value; }
        }

        public SortDirection directionState
        {
            get { return (ViewState["directionState"] == null ? SortDirection.Descending : (SortDirection)ViewState["directionState"]); }
            set { ViewState["directionState"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            setClearMsgAll();
            if (!IsPostBack)
            {
                BindData_Function(null);
                BindData_UserPolicy();
                BindData_FuncPolicy();
            }
        }

        public void setClearMsgAll()
        {
            MsgUC11.setClearMsg(true);
            MsgUC22.setClearMsg(true);
            MsgUC33.setClearMsg(true);
            MsgUC44.setClearMsg(true);
            MsgUC9.setClearMsg(true);
        }

        #region "Function"
        private void BindData_Function(String sSortColumn)
        {
            try
            {
                DataTable dt = (new ShareDAO.FuncDAO()).SelectList();
                DataView dv = dt.DefaultView;
                if (!String.IsNullOrEmpty(sSortColumn))
                    dv.Sort = sSortColumn;
                else
                    dv.Sort = "[PK_iFunctionID] DESC";
                dt = dv.ToTable();
                if (dt.Rows.Count <= 0)
                    dt.Rows.Add(dt.NewRow());

                dt.Columns.Add(new DataColumn("sLink", Type.GetType("System.String")));
                foreach (DataRow item in dt.Rows)
                {
                    item["sLink"] = "~/admin/accessui.aspx?r=" + System.Web.HttpContext.Current.Server.UrlEncode(Security.Login.Encrypt(Convert.ToString(item["PK_iFunctionID"]), System.Configuration.ConfigurationManager.AppSettings["PRIVATE_KEY"]));
                }
                grvF_List.DataSource = dt;
                grvF_List.DataBind();
                lblRowCount.Text = MessagesEx.Tong_So_Ban_Ghi + dt.Rows.Count;
            }
            catch (Exception ex)
            {
                MsgUC11.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        protected void btnInsert_Click(object sender, EventArgs e)
        {
            setClearMsgAll();
            try
            {
                FuncEO objTemp = new FuncEO();
                objTemp.PK_iFunctionID = 0;
                objTemp.sName = ((TextBox)grvF_List.FooterRow.FindControl("txtsName_I")).Text;
                objTemp.sPath = OtherEx.RemoveDomainInUrl(((TextBox)grvF_List.FooterRow.FindControl("txtsPath_I")).Text);
                objTemp.iAppID = Convert.ToInt32(((TextBox)grvF_List.FooterRow.FindControl("txtiAppID_I")).Text);
                objTemp.iParentID = Convert.ToInt32(((TextBox)grvF_List.FooterRow.FindControl("txtiParentID_I")).Text);
                objTemp.iRole = Convert.ToInt32(((TextBox)grvF_List.FooterRow.FindControl("txtiRole_I")).Text);
                objTemp.bStatus = ((CheckBox)grvF_List.FooterRow.FindControl("chkbStatus_I")).Checked;
                if (CheckInput(ref objTemp))
                {
                    if ((new ShareDAO.FuncDAO()).Insert_Update_Delete(objTemp, 1))
                        MsgUC11.setNotifications(ConstEx.FunctionSetMsg.SUCCESS, "Thêm thành công!");
                    else
                        MsgUC11.setNotifications(ConstEx.FunctionSetMsg.WARNING, "Thêm thất bại!");
                    BindData_Function(null);
                }
            }
            catch (Exception ex)
            {
                MsgUC11.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        protected void lbtnDelete_Click(object sender, EventArgs e)
        {
            setClearMsgAll();
            try
            {
                FuncEO objTemp = new FuncEO();
                LinkButton lbtnDelete = (LinkButton)sender;
                objTemp.PK_iFunctionID = Convert.ToInt32(lbtnDelete.CommandArgument);
                if ((new ShareDAO.FuncDAO()).Insert_Update_Delete(objTemp, 3))
                    MsgUC11.setNotifications(ConstEx.FunctionSetMsg.SUCCESS, "Xóa thành công!");
                else
                    MsgUC11.setNotifications(ConstEx.FunctionSetMsg.WARNING, "Xóa thất bại!");
                BindData_Function(null);
            }
            catch (Exception ex)
            {
                MsgUC11.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        protected void grvF_List_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvF_List.PageIndex = e.NewPageIndex;
            BindData_Function(null);
        }

        protected void grvF_List_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grvF_List.EditIndex = -1;
            BindData_Function(null);
        }

        protected void grvF_List_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grvF_List.EditIndex = e.NewEditIndex;
            BindData_Function(null);
        }

        protected void grvF_List_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            setClearMsgAll();
            try
            {
                FuncEO objTemp = new FuncEO();
                objTemp.PK_iFunctionID = Convert.ToInt32(((Label)grvF_List.Rows[e.RowIndex].FindControl("lblPK_iFunctionID_V")).Text);
                objTemp.sName = ((TextBox)grvF_List.Rows[e.RowIndex].FindControl("txtsName_U")).Text;
                objTemp.sPath = OtherEx.RemoveDomainInUrl(((TextBox)grvF_List.Rows[e.RowIndex].FindControl("txtsPath_U")).Text);
                objTemp.iAppID = Convert.ToInt32(((TextBox)grvF_List.Rows[e.RowIndex].FindControl("txtiAppID_U")).Text);
                objTemp.iParentID = Convert.ToInt32(((TextBox)grvF_List.Rows[e.RowIndex].FindControl("txtiParentID_U")).Text);
                objTemp.iRole = Convert.ToInt32(((TextBox)grvF_List.Rows[e.RowIndex].FindControl("txtiRole_U")).Text);
                objTemp.bStatus = ((CheckBox)grvF_List.Rows[e.RowIndex].FindControl("chkbStatus_U")).Checked;
                if (CheckInput(ref objTemp))
                {
                    if ((new ShareDAO.FuncDAO()).Insert_Update_Delete(objTemp, 2))
                        MsgUC11.setNotifications(ConstEx.FunctionSetMsg.SUCCESS, "Sửa thành công!");
                    else
                        MsgUC11.setNotifications(ConstEx.FunctionSetMsg.WARNING, "Sửa thất bại!");
                    grvF_List.EditIndex = -1;
                    BindData_Function(null);
                }
            }
            catch (Exception ex)
            {
                MsgUC11.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        protected void grvF_List_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (directionState == SortDirection.Ascending)
            {
                directionState = SortDirection.Descending;
                BindData_Function("[" + e.SortExpression + "]" + " DESC");
            }
            else
            {
                directionState = SortDirection.Ascending;
                BindData_Function("[" + e.SortExpression + "]" + " ASC");
            }
        }

        public Boolean CheckInput(ref FuncEO objFuncEO)
        {
            String strNull = "";
            if (String.IsNullOrEmpty(objFuncEO.sName))
                strNull += ", Tên CN";
            if (String.IsNullOrEmpty(objFuncEO.sPath))
                strNull += ", Đường dẫn";
            if (objFuncEO.iAppID <= 0)
                strNull += ", Mã ứng dụng";
            if (objFuncEO.iParentID <= 0)
                strNull += ", Nhóm chức năng";
            if (objFuncEO.iRole <= 0)
                strNull += ", Nhóm quyền";

            objFuncEO.sPath = StringEx.Trim(objFuncEO.sPath).ToLower().Replace("~/usercontrol/", "");


            //if (StringEx.CompareEx(objFuncEO.sPath, "UserControl/Admin/"))
            //    if (!StringEx.CompareEx(objFuncEO.sPath, "~/"))
            //        objFuncEO.sPath = "~/" + objFuncEO.sPath;
            //    else
            //        objFuncEO.sPath = objFuncEO.sPath;
            //else
            //    objFuncEO.sPath = "~/usercontrol/admin/" + objFuncEO.sPath;

            if (String.IsNullOrEmpty(strNull))
            {
                if (!File.Exists(Server.MapPath(OtherEx.getAppSettings("RawUrl_UC", "~/usercontrol/") + objFuncEO.sPath)))
                    MsgUC11.setNotifications(ConstEx.FunctionSetMsg.WARNING, "Đường dẫn không tồn tại: " + Server.MapPath(OtherEx.getAppSettings("RawUrl_UC", "~/usercontrol/") + objFuncEO.sPath), null);
                else
                    return true;
                return false;
            }
            else
            {
                MsgUC11.setNotifications(ConstEx.FunctionSetMsg.WARNING, MessagesEx.CAC_TRUONG_BAT_BUOC_PHAI_NHAP + strNull.Substring(2).Replace(":", ""), null);
                return false;
            }
        }

        #endregion

        #region "Account"
        #endregion

        #region "UserPolicy"
        private void BindData_UserPolicy()
        {
            try
            {
                ddlUP_ListUser.DataSource = (new ShareDAO.UserDAO()).SelectBy_bState(null);
                ddlUP_ListUser.DataValueField = "PK_iAccountID";
                ddlUP_ListUser.DataTextField = "sUsername";
                ddlUP_ListUser.DataBind();

                cblUP_ListFunc.DataSource = (new ShareDAO.FuncDAO()).SelectList();
                cblUP_ListFunc.DataValueField = "PK_iFunctionID";
                cblUP_ListFunc.DataTextField = "sName";
                cblUP_ListFunc.DataBind();

                rblRole.DataSource = GetListConstants.Account_iPermission_GLC();
                rblRole.DataValueField = "Key";
                rblRole.DataTextField = "Value";
                rblRole.DataBind();

                BindDetail_UserPolicy();
            }
            catch (Exception ex)
            {
                MsgUC33.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        private void BindDetail_UserPolicy()
        {
            setClearMsgAll();
            try
            {
                Int32 iTemp = 0;
                if (Int32.TryParse(ddlUP_ListUser.SelectedValue, out iTemp))
                    objTemp = (new ShareDAO.UserDAO()).SelectItem(iTemp, null);
                if (objTemp != null)
                {
                    objTemp.sDescription = Security.Login.Decrypt(objTemp.sPermission, Security.Insert_Salt(objTemp.tDateOfReg.ToString(FormatEx.Date_Time.Format_DateTime_Ex), objTemp.PK_iAccountID.ToString()));
                    WebEx.setSelect_ListCheckBox(cblUP_ListFunc, objTemp.sDescription);
                    rblRole.SelectedValue = objTemp.iPermission.ToString();
                    return;
                }
                MsgUC33.setNotifications(ConstEx.FunctionSetMsg.WARNING, "Tài khoản không tồn tại.");
            }
            catch (Exception ex)
            {
                WebEx.setSelect_ListCheckBox(cblUP_ListFunc, "");
                rblRole.SelectedValue = Convert.ToString(Account_iPermission_C.Anonymous);
                MsgUC33.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        protected void btnUP_Update_Click(object sender, EventArgs e)
        {
            setClearMsgAll();
            try
            {
                objTemp.sPermission = WebEx.getSelect_ListCheckBox(cblUP_ListFunc, true);
                objTemp.sPermission = Security.Login.Encrypt(objTemp.sPermission, Security.Insert_Salt(objTemp.tDateOfReg.ToString(FormatEx.Date_Time.Format_DateTime_Ex), objTemp.PK_iAccountID.ToString()));
                Int16 iTemp = 0;
                if (Int16.TryParse(rblRole.SelectedValue, out iTemp))
                    objTemp.iPermission = iTemp;
                else
                    MsgUC33.setNotifications(ConstEx.FunctionSetMsg.WARNING, "Chưa chọn nhóm tài khoản.");
                if ((new ShareDAO.UserDAO()).Update_Permission(objTemp))
                    MsgUC33.setNotifications(ConstEx.FunctionSetMsg.SUCCESS, "Cập nhật thành công.");
                else
                    MsgUC33.setNotifications(ConstEx.FunctionSetMsg.WARNING, "Cập nhật thất bại.");
            }
            catch (Exception ex)
            {
                MsgUC33.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        protected void ddlUP_ListUser_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindDetail_UserPolicy();
        }
        #endregion

        #region "FuncPolicy"
        private void BindData_FuncPolicy()
        {
            try
            {
                ddlFP_ListFunc.DataSource = (new ShareDAO.FuncDAO()).SelectList();
                ddlFP_ListFunc.DataValueField = "PK_iFunctionID";
                ddlFP_ListFunc.DataTextField = "sName";
                ddlFP_ListFunc.DataBind();

                cblFP_ListUser.DataSource = (new ShareDAO.UserDAO()).SelectBy_bState(null);
                cblFP_ListUser.DataValueField = "PK_iAccountID";
                cblFP_ListUser.DataTextField = "sUsername";
                cblFP_ListUser.DataBind();
            }
            catch (Exception ex)
            {
                //MsgUC1.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        protected void btnFP_Update_Click(object sender, EventArgs e)
        {
            String _lstFunc = WebEx.getSelect_ListCheckBox(cblUP_ListFunc, true);
            String _lstFunc_Encrypt = Security.Login.Encrypt(_lstFunc, Security.Insert_Salt(objTemp.tDateOfReg.ToString(FormatEx.Date_Time.Format_DateTime_Ex), objTemp.PK_iAccountID.ToString()));
        }
        #endregion
    }
}